<template>
  <el-dialog :visible.sync="dialogVisible" :title="title" @opened="handleDialogOpened" width="90%"
             :close-on-click-modal="false">
    <el-tabs>
      <el-tab-pane :label="template.name" v-for="(template, index) of templateList" :key="index">
        <div class="cam__gen_preview_content">{{ template.data }}</div>
      </el-tab-pane>
    </el-tabs>

    <div slot="footer">
      <el-button type="primary" size="small" @click="download">下载</el-button>
      <el-button size="small" @click="dialogVisible = false">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'GenCodePreview',
  props: {
    genId: {
      type: String,
      required: true
    },
    method: {
      type: String,
      required: true
    },
    visible: {
      type: Boolean,
      required: true
    },
    version: {
      type: String,
      required: true
    }
  },
  computed: {
    loading () {
      return this.process.formLoading
    },
    editAble () {
      return this.method === 'add' || this.method === 'edit'
    },
    dialogVisible: {
      set (value) {
        this.$emit('update:visible', value)
      },
      get () {
        return this.visible
      }
    },
    title () {
      if (this.method === 'view') {
        return '代码预览'
      } else if (this.method === 'add') {
        return '代码预览'
      } else if (this.method === 'edit') {
        return '代码预览'
      } else {
        return ''
      }
    }
  },
  data () {
    return {
      activeTab: '',
      templateList: []
    }
  },
  methods: {
    handleDialogOpened () {
      this.reset()
      if (this.genId) {
        this.loadData()
      }
    },
    reset () {
      Object.assign(this.$data, this.$options.data())
    },
    loadData () {
      let url
      if (this.version === '1x') url = `/generator/code/previewFor1x?id=${this.genId}`
      if (this.version === 'iot1x') url = `/generator/code/previewForIot1x?id=${this.genId}`
      if (this.version === 'jeeplus9x') url = `/generator/code/previewForJeeplus9x?id=${this.genId}`
      if (this.version === 'jeeplus8x') url = `/generator/code/previewForJeeplus8x?id=${this.genId}`
      this.$http.get(url).then(({ data }) => {
        console.log(data)
        this.templateList = data.data
      })
    },
    download () {
      let url
      if (this.version === '1x') url = `/generator/code/downloadFor1x?id=${this.genId}`
      if (this.version === 'iot1x') url = `/generator/code/downloadForIot1x?id=${this.genId}`
      if (this.version === 'jeeplus9x') url = `/generator/code/downloadForJeeplus9x?id=${this.genId}`
      if (this.version === 'jeeplus8x') url = `/generator/code/downloadForJeeplus8x?id=${this.genId}`
      this.$http.download(url)
    }
  }
}
</script>

<style scoped lang="scss">
.cam__gen_preview_content {
  white-space: pre-wrap;
}
</style>
